/**
 * Created by asus on 2017/6/10.
 */
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


public class Study {
    static final int NPREF = 2;
    static final String NOWORD = "*";
    Map<Front,List<String>> stateTable = new HashMap<Front,List<String>>();
    Front fronts = new Front(NPREF,NOWORD);
    Random random = new Random();


    public void build(InputStream in) throws Exception {
        long time1= Calendar.getInstance().getTimeInMillis();
        Scanner scanner = new Scanner(in);

        while(scanner.hasNext()){
            add(scanner.next());
        }
        add(NOWORD);
        long time2 = Calendar.getInstance().getTimeInMillis();
        System.out.print("学习文章：");
        System.out.println(time2-time1 + "ms");
    }

    private void add(String word) {
        List<String> suf = stateTable.get(fronts);
        if(suf == null){
            suf = new ArrayList<String>();
            stateTable.put(new Front(fronts),suf);
        }
        suf.add(word);
        fronts.front.remove(0);
        fronts.front.add(word);
    }


    public void generate(int nwords,String name,List<String>list) throws IOException {
        long time1= Calendar.getInstance().getTimeInMillis();
        FileWriter fw = new FileWriter(name);
        fronts = new Front(NPREF,NOWORD);

        fronts.front.remove(0);
        fronts.front.add(list.get(0));
        fronts.front.remove(0);
        fronts.front.add(list.get(1));

        fw.write(list.get(0)+" "+list.get(1)+" ");

        for(int i=0; i<nwords; i++){
            List<String> suf = stateTable.get(fronts);

            int r = Math.abs(random.nextInt(suf.size()));

            String word = suf.get(r);
            if(word.equals(NOWORD)){
                break;
            }
            else
                fw.write(word+" ");
            fronts.front.remove(0);
            fronts.front.add(word);

        }
        fw.close();
        long time2 = Calendar.getInstance().getTimeInMillis();
        System.out.print("写出：");
        System.out.println(time2-time1 + "ms");
    }

}
